package com.laundry.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/db")
@RequiredArgsConstructor
public class DatabaseViewController {
    
    private final JdbcTemplate jdbcTemplate;
    
    @GetMapping("/console")
    public String console() {
        return "db-console";
    }
    
    @PostMapping("/query")
    @ResponseBody
    public Map<String, Object> executeQuery(@RequestParam String sql) {
        try {
            if (sql.trim().toUpperCase().startsWith("SELECT")) {
                List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
                return Map.of("success", true, "data", result, "type", "query");
            } else {
                int rows = jdbcTemplate.update(sql);
                return Map.of("success", true, "data", "影响行数: " + rows, "type", "update");
            }
        } catch (Exception e) {
            return Map.of("success", false, "error", e.getMessage());
        }
    }
    
    @GetMapping("/tables")
    @ResponseBody
    public Map<String, Object> getTables() {
        try {
            List<Map<String, Object>> tables = jdbcTemplate.queryForList(
                "SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PUBLIC' ORDER BY TABLE_NAME"
            );
            return Map.of("success", true, "data", tables);
        } catch (Exception e) {
            return Map.of("success", false, "error", e.getMessage());
        }
    }
    
    @GetMapping("/table/{tableName}")
    @ResponseBody
    public Map<String, Object> getTableData(@RequestParam String tableName) {
        try {
            List<Map<String, Object>> data = jdbcTemplate.queryForList("SELECT * FROM " + tableName + " LIMIT 100");
            return Map.of("success", true, "data", data);
        } catch (Exception e) {
            return Map.of("success", false, "error", e.getMessage());
        }
    }
}
